package com.playcrab.adouban;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity; 
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

import com.google.gdata.client.douban.DoubanService;
import com.google.gdata.data.Link;
import com.google.gdata.data.TextContent;
import com.google.gdata.data.douban.UserEntry;
import com.google.gdata.data.douban.UserFeed;
import com.google.gdata.util.ServiceException;

public class FriendList extends BaseActivity {
	private static final int COUNT_ITEMS_PER_PAGE = 15;
	private static final String LOG_TAG = "FriendList";

	private ListView firendList; 
	FriendListAdapter friendListAdapter = null;
	private Handler handler = new Handler();
	String query;
	String type;
	UserFeed feed;
	List<UserEntry> friends;

	public List<UserEntry> getFriends() {
		return friends;
	}

	public void setFriends(List<UserEntry> friends) {
		this.friends = friends;
	}

	int currentStartIndex = 1;

	private static final int MENU_SEARCH = Menu.FIRST + 1;
	private static final int MENU_SCAN = Menu.FIRST + 2;

	public static final int MENU_RETURN = Menu.FIRST + 10;

	public static final int MENU_REPLY = Menu.FIRST + 7;
	public static final int MENU_DELETE = Menu.FIRST + 8;
	private static final int MENU_VIEW_FRIEND = Menu.FIRST + 100;
	private static final int MENU_DELETE_FRIEND = Menu.FIRST + 101;
	private static final int MENU_SEND_DOUMAIL = Menu.FIRST + 102;
	private static final int MENU_EXIT = Menu.FIRST + 103;
	private static final int MENU_REFRESH = Menu.FIRST + 104;
	public class FriendListAdapter extends AutoRefreshAdapter<UserEntry> {

		private static final String LOG_TAG = "FriendListAdapter";
		Activity context;
		LayoutInflater inflater;
		WebView userIcon;
		TextView username, replyTo, updateBody, via, timestamp;
		List<UserEntry> more_cols;

		public FriendListAdapter(Activity context, List<UserEntry> friends) {
			super(context, friends);
			inflater = LayoutInflater.from(context);

			this.context = context;
			this.itemList = friends;
			// TODO Auto-generated constructor stub
		}

		 
		@Override
		public View getItemView(int position) {
			View row = inflater.inflate(R.layout.friend_row, null);
			row.setLongClickable(true);
			row.setClickable(true);

			final UserEntry se = itemList.get(position);
			List<Link> links = se.getLinks();

			row.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View arg0) {
					String sid = se.getUid();
					FriendList.this.viewUser(sid); 
				}

			}); 
			
			row.setTag(se);
			if (se == null) {
				return row;
			}  
			
			WebView  image = (WebView) row.findViewById(R.id.friend_image);
			
			String iconUrl = "http://t.douban.com/icon/user.jpg";
			if(se.getLink("icon",null) != null){
				iconUrl = se.getLink("icon", null).getHref();
			} 
			image.loadUrl(iconUrl); 
			
			
			if(se.getLink("homepage",null) != null){
				TextView hompage  = (TextView) row.findViewById(R.id.friend_homepage);
				hompage.setText(getString(R.string.homepage_hint).concat(se.getLink("homepage",null).getHref()));
			} 
			
			TextView title  = (TextView) row.findViewById(R.id.friend_title);
			title.setText(se.getTitle().getPlainText());
			
			if(se.getLocation()!=null){
				TextView location  = (TextView) row.findViewById(R.id.friend_location);
				location.setText(se.getLocation());
			}
 			
			return row;

		} 

		public void addFriends(List<UserEntry> subs) {
			// TODO Auto-generated method stub
			itemList.addAll(itemList.size(), subs);
			notifyDataSetChanged();
		}

		protected boolean cacheInBackground() {
			more_cols = FriendList.this.updateFriends();

			return (more_cols.size() == FriendList.COUNT_ITEMS_PER_PAGE);
		}

		protected void appendCachedData() {
			addFriends(more_cols);
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.friend_list);

		Bundle bundle = this.getIntent().getExtras();
		type = bundle.getString("type");
		userId = bundle.getString("id");
		
		
		
		if(userId == null)
			 userId = getStoredUserId();
		
		if(type == null)
			 type = "friends";
		
		if(type.equals("friends")){
			setTitle(userId.concat("的").concat(getString(R.string.friends)));
		}else if(type.equals("contacts")){
			setTitle(userId.concat("的").concat(getString(R.string.contacts)));
		}
		
		firendList = (ListView) findViewById(R.id.friend_list);

		registerForContextMenu(firendList);
		
		friendListAdapter = new FriendListAdapter(
				FriendList.this, new ArrayList<UserEntry>());
		firendList.setAdapter(friendListAdapter);

//		progressDialog = ProgressDialog.show(FriendList.this, FriendList.this
//				.getResources().getText(R.string.waiting), FriendList.this
//				.getResources().getText(R.string.searching), true);
//
//		new Thread() {
//			public void run() {
//				friends = updateFriends();
//				progressDialog.dismiss();
//				handler.post(new Runnable() {
//					public void run() {
//						friendListAdapter = new FriendListAdapter(
//								FriendList.this, friends);
//						firendList.setAdapter(friendListAdapter);
//					}
//				});
//
//			}
//		}.start();

		InsertPanel();
	}
	
	public void refreshFriends(){
		if (this.friendListAdapter == null
				|| this.friendListAdapter.itemList == null)
			return ;
		Toast.makeText(
				getApplicationContext(),
				this.getResources().getText(
						R.string.waiting),
				Toast.LENGTH_SHORT).show();
 
		new Thread() {
			public void run() { 
				friends = updateFriends(1);  
				FriendList.this.friendListAdapter.itemList.clear();
				FriendList.this.friendListAdapter.itemList.addAll(friends); 
				handler.post(new Runnable() {
					public void run() {
						FriendList.this.friendListAdapter.notifyDataSetChanged();
					}
				});
			 
			}
		}.start(); 
		 
	}
	
	protected List<UserEntry> updateFriends(int startIndex) { 
		currentStartIndex = startIndex; 
	
		DoubanService service = getAuthedDoubanService();// DoubanAPI.getInstance().getService();
		if (service == null) {
			return new ArrayList();
		}
		try {
			if(type.equals("contacts")){
				feed = service.getUserContacts(userId, FriendList.this.currentStartIndex,
						COUNT_ITEMS_PER_PAGE);
			}else{
			feed = service.getUserFriends(userId, FriendList.this.currentStartIndex,
					COUNT_ITEMS_PER_PAGE);
			}
			
			friends = feed.getEntries();
			return friends;

		} catch (IOException e) {
			e.printStackTrace();
			this.showInfo(getString(R.string.network_error));
		} catch (ServiceException e) {
			e.printStackTrace();
			this.showInfo(getString(R.string.service_error));
		} finally {
		}
		return new ArrayList();
	}


	protected List<UserEntry> updateFriends() {
		int currentStartIndex = 1;
		if (this.friendListAdapter == null
				|| this.friendListAdapter.itemList == null)
			currentStartIndex = 1;
		else
			currentStartIndex = this.friendListAdapter.itemList.size() + 1;
	 
		return updateFriends(currentStartIndex);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		menu.setHeaderTitle("操作菜单");
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		menu.add(0, MENU_VIEW_FRIEND, 0, "查看");
		menu.add(0, MENU_SEND_DOUMAIL, 0, "发送豆邮");
		 

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		UserEntry se = this.friendListAdapter.itemList.get(info.position);
		switch (item.getItemId()) {
		case MENU_VIEW_FRIEND: {
			String sid =  se.getUid();
			FriendList.this.viewUser(sid);
			return true;
		}
		case MENU_SEND_DOUMAIL:{
			String sid =  se.getId();
			Intent i = new Intent(FriendList.this, ComposeDoumail.class);
			String userTitle = se.getTitle().getPlainText();
			i.putExtra("to", sid );
			i.putExtra("toUserTitle", userTitle);
			startActivity(i);
			return true;
		}

		}
		return super.onOptionsItemSelected(item);

	}
	 

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_REFRESH: {
			this.refreshFriends();
			return true;
		}
		case MENU_EXIT: {
			this.finish();
		}

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_REFRESH, 0, "刷新").setIcon(android.R.drawable.ic_menu_rotate)
		.setAlphabeticShortcut('R'); 
		menu.add(0, MENU_EXIT, 0, "返回").setIcon(android.R.drawable.ic_menu_close_clear_cancel)
				.setAlphabeticShortcut('X'); 
		return true;
	}

}
